<?php
namespace App\Api\Service\Trigonal;

use App\Models\Log\LogUserPay;

use Yansongda\Pay\Pay;

/**
 * 支付类
 */
class WxpayService{
    protected $config;

    public function __construct(){
        $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $url = config("app.url");
        $this->config = [
            'wechat' => [
                'default' => [
                    // 必填-商户号，服务商模式下为服务商商户号
                    'mch_id' => $sys_setting_repositories->get(40),
                    // 必填-商户秘钥
                    'mch_secret_key' => $sys_setting_repositories->get(41),
                    // 必填-商户私钥 字符串或路径
                    'mch_secret_cert' => './cert/apiclient_key.pem',
                    // 必填-商户公钥证书路径
                    'mch_public_cert_path' => './cert/apiclient_cert.pem',
                    // 必填
                    'notify_url' => $url . '/api/pay/notify',
                    // 选填-公众号 的 app_id
                    'mp_app_id' => '',
                    // 选填-小程序 的 app_id
                    'mini_app_id' => $sys_setting_repositories->get(16),
                    // 选填-app 的 app_id
                    'app_id' => '',
                    // 选填-微信公钥证书路径, optional，强烈建议 php-fpm 模式下配置此参数
                    'wechat_public_cert_path' => [
                        $sys_setting_repositories->get(42) => __DIR__.'/Cert/wechatPublicKey.crt',
                    ],
                    // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SERVICE
                    'mode' => Pay::MODE_NORMAL,
                ]
            ],
            'logger' => [ // optional
                'enable' => false,
                'file' => './logs/wechat.log',
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ],
        ];
    }

    /**
     * 发起支付请求
     *
     * @param int $uid 会员id
     * @param int $integral 积分id
     * @return void
     */
    public function pay($uid, $integral){
        // 创建支付订单
        $order_no = 'r' . date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $money = $sys_setting_repositories->get_money($integral);
        $log_user_pay_repositories = new \App\Api\Repositories\Log\LogUserPayRepositories();
        if(!$log_user_pay_repositories->create_data($order_no, $uid, $integral, $money)){
            throwBusinessException('操作失败');
        }
        // 构建微信支付订单
        $user_repositories = new \App\Api\Repositories\User\UsersRepositories();
        $user = $user_repositories->get_data('id', $uid, ['openid']);
        $order = [
            'out_trade_no'=> $order_no,
            '_config' => 'default',
            'description'=> '充值',
            'amount' => [
                'total' => floatval($money) * 100,
                'currency' => 'CNY',
            ],
            'payer' => [
                'openid' => $user->openid,
            ]
        ];
        Pay::config($this->config);
        $result = Pay::wechat()->mini($order);
        return $result;
    }

    public function pay_show_contact($uid, $search_id, $type){
        $order_no = 'c' . date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        // 获取需要的金额，并添加一个未支付的记录
        $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $need_money = $sys_setting_repositories->get(25);
        $LogPayShowContactRepositories = new \App\Api\Repositories\Log\LogPayShowContactRepositories();
        if(!$LogPayShowContactRepositories->create_data($order_no, $uid, $search_id, $type)){
            throwBusinessException('操作失败');
        }
        // 构建微信支付订单
        $user_repositories = new \App\Api\Repositories\User\UsersRepositories();
        $user = $user_repositories->get_data('id', $uid, ['openid']);
        $order = [
            'out_trade_no'=> $order_no,
            '_config' => 'default',
            'description'=> '查看信息',
            'amount' => [
                'total' => floatval($need_money) * 100,
                'currency' => 'CNY',
            ],
            'payer' => [
                'openid' => $user->openid,
            ]
        ];
        Pay::config($this->config);
        $result = Pay::wechat()->mini($order);
        return $result;
    }

    /**
     * 支付回调
     *
     * @return void
     */
    public function pay_notify(){
        Pay::config($this->config);
        try{
            $data = Pay::wechat()->callback();
            $data = json_decode(json_encode($data));
            $order_no = $data->resource->ciphertext->out_trade_no;
            if(substr($order_no, 0, 1) == 'r'){
                // 充值
                $log_user_pay_repositories = new \App\Api\Repositories\Log\LogUserPayRepositories();
                $order = $log_user_pay_repositories->use_field_select_data('order_no', $order_no);
                if(!$order || $order->status != 1){
                    return Pay::wechat()->success();
                }
                $log_user_pay_repositories->update_fields($order, ['status'=> 2]);
                $user_fund_repositories = new \App\Api\Repositories\User\UserFundsRepositories();
                $user_fund_repositories->update_data($order->uid, 'money', $order->money, '充值', '充值');
            }else{
                // 支付查看联系方式
                $LogPayShowContactRepositories = new \App\Api\Repositories\Log\LogPayShowContactRepositories();
                $log = $LogPayShowContactRepositories->use_id_get_data($order_no);
                if(!$log || $log->status != 0){
                    return Pay::wechat()->success();
                }
                $LogPayShowContactRepositories->update_fields($log, ['status'=> 1]);
            }
            return Pay::wechat()->success();
        } catch (\Exception $e) {
        }
        return false;
    }
}
